package com.inc.admin.filters;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.util.StreamUtils;



public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
    //使用HttpServletRequestWrapper重写Request请求参数

    private final byte[] body;

    private String bodyString;

    public MyHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        //  spring接到浏览器传来的post请求 所传进来的参数都在request里
        //request.getInputStream()的值是全部请求信息 但是并非我们想要是参数
        super(request);
        this.bodyString = StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8"));
        body = bodyString.getBytes("UTF-8");
    }

    public String getBodyString() {
        return this.bodyString;
    }
   /*
   下面的方法是处理  前端传递的是图片的情况
    */
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
        //读取数据 图片的数据

    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body);//读取数据
        //字节数组输入流在内存中创建一个字节数组缓冲区，从输入流读取的数据保存在该字节数组缓冲区中

        return new ServletInputStream() {
            //ServletInputStream()输入流读取图片

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
                //从此输入流中读取下一个数据字节。
            }
        };
    }

}
